package com.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Base64;

public class AES_EUnit {
    private static final int AES_BLOCK_SIZE = 16;
    public static byte[] AES_E( byte[] message, byte[] key, int mLen) {
        try {
            // 创建AES密钥
            SecretKeySpec secretKey = new SecretKeySpec(key, "AES");

            // 创建初始化向量
            byte[] iv = new byte[AES_BLOCK_SIZE];
            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            // 创建AES密码器
            Cipher aesCipher = Cipher.getInstance("AES/CBC/NoPadding");
            aesCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);

            // 执行加密
            byte[] encryptedMessage = aesCipher.doFinal(message, 0, mLen);
//            String str = Base64.getEncoder().encodeToString(encryptedMessage);
//            int encryptedLength = aesCipher.doFinal(message,0,mLen,encryptedMessage,0);
//            StoreUnit.LR.put(str,encryptedLength);
//            System.out.println("加密后的数据长度是"+encryptedLength);
            return encryptedMessage;
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }

    public static void AES_D(byte[] Message, int messagePos, byte[] data, byte[] key, int length) {
        try {
            // 创建AES密钥
            SecretKeySpec secretKey = new SecretKeySpec(key, "AES");

            // 创建初始化向量IV
            byte[] iv = new byte[AES_BLOCK_SIZE];

            // 初始化密码器
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);

            // 解密数据
            byte[] decryptedData = cipher.doFinal(data, 0, length);

            System.out.println("decryptedData的长度是"+decryptedData.length);

            // 将解密后的数据复制到Message数组中
            System.arraycopy(decryptedData, 0, Message, messagePos, decryptedData.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
